// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

mod core;
mod extensions;
// mod plugins;

use std::sync::Arc;
use tauri::Manager;

use crate::core::expansion_system::{ExpansionSystem, ExpansionSystemOptions};
use crate::core::manifest::{ActivationEventDefinition, ExpansionManifest};
use crate::extensions::commands::manifest::create_commands_manifest;
use crate::extensions::streams::manifest::create_streams_manifest;


#[tokio::main]
async fn main() {
    // 1. 收集所有内置插件的清单
    let manifests: Vec<ExpansionManifest> = vec![
        create_commands_manifest(),
        create_streams_manifest(),
    ];

    // 2. 定义系统的激活事件
    let activation_event_definitions: Vec<ActivationEventDefinition> = vec![
        ActivationEventDefinition {
            name: "system.startup".to_string(),
            pre_activation_events: None,
        }
    ];

    // 3. 创建微内核配置
    let options = ExpansionSystemOptions {
        manifests,
        activation_event_definitions,
    };

    // 4. 创建并启动微内核
    let system = ExpansionSystem::new(options);
    println!("ExpansionSystem created. Activating startup plugins...");
    system.activate("system.startup", false).await;
    println!("Startup plugins activated.");

    // 5. 启动 Tauri 应用
    let app = tauri::Builder::default()
        .manage(system) // 将内核实例放入 Tauri 的状态管理
        .on_window_event(|window, event| {
            if let tauri::WindowEvent::CloseRequested { .. } = event {
                println!("Tauri window close requested. Destroying ExpansionSystem...");
                let system = window.state::<Arc<ExpansionSystem>>();
                system.destroy();
                // allow the window to be closed
            }
        })
        .invoke_handler(tauri::generate_handler![])
        .build(tauri::generate_context!())
        .expect("error while building tauri application");

    app.run(|_app_handle, _event| {});
}
